/**
 * When context isolation is enabled, IPC messages from the main process to 
 * the renderer are delivered to the isolated world, 
 * rather than to the main world. 
 * Sometimes you want to deliver messages to the main world directly, 
 * without having to step through the isolated world.
 */

const { BrowserWindow, app, MessageChannelMain } = require('electron')
const pathModule = require('path')

app.whenReady().then(async () => {
  const bw = new BrowserWindow({
    webPreferences: {
      contextIsolation: true,
      preload: pathModule.join(__dirname, 'preload', 'isoMsgPreload.js')
    }
  })
  bw.loadURL(pathModule.join(__dirname, 'render', 'isoIndex.html'))

  bw.webContents.openDevTools()

  const { port1, port2 } = new MessageChannelMain()

  // it is ok to send a message on the channel before the other end has registered a listener.
  // messages will be queued unti a listener is registered.
  port2.postMessage({
    test: 21
  })

  // receive messages from the main world of the renderer.
  port2.on('message', (event) => {
    console.info('from renderer main world: ', event.data)
  })

  port2.start()

  // the preload script will receive this IPC message 
  // and transfer the port over to the main world.
  bw.webContents.postMessage('main-world-port', null, [port1])
})